package com.leyou.search.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.*;
import com.leyou.search.dto.GoodsDTO;
import com.leyou.search.dto.SearchRequest;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.SearchRepository;
import com.leyou.search.utils.HighlightUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchService {

    @Autowired
    private SearchRepository searchRepository;

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Autowired
    private ItemClient itemClient;

    /**
     * 把一个SpuDTO对象转成Goods对象
     */
    public Goods buildGoods(SpuDTO spuDTO){
        //根据SpuId查询Sku集合
        List<Sku> skus = itemClient.findSkusBySpuId(spuDTO.getId());
        //创建一个sku的map的list集合
        List<Map<String, Object>> skuMaps = new ArrayList<>();
        //遍历skus
        skus.forEach(sku -> {
            Map<String, Object> skuMap = new HashMap<>();
            skuMap.put("id", sku.getId());
            skuMap.put("image", StringUtils.substringBefore(sku.getImages(), ","));
            skuMap.put("price", sku.getPrice());
            skuMap.put("title", sku.getTitle().substring(spuDTO.getName().length()));
            //把skuMap放入skuMaps
            skuMaps.add(skuMap);
        });

        //封装sku的价格的集合
        Set<Long> prices = skus.stream().map(Sku::getPrice).collect(Collectors.toSet());

        //封装all字段
        String all = spuDTO.getBrandName()
                + spuDTO.getCategoryName()
                + spuDTO.getSubTitle()
                + skus.stream().map(Sku::getTitle).collect(Collectors.joining());

        //封装过滤条件
        Map<String, Object> specs = new HashMap<>();
        //根据分类id查询参与搜索的规格参数
        List<SpecParam> specParams = itemClient.findSpecParams(null, spuDTO.getCid3(), true);
        //根据SpuId查询SpuDetail对象
        SpuDetail spuDetail = itemClient.findSpuDetailById(spuDTO.getId());
        //获取通用规格参数值的字符串类型
        String genericSpecStr = spuDetail.getGenericSpec();
        //将字符串类型的通用规格参数转成对象
        Map<Long, Object> genericSpecObj = JsonUtils.toMap(genericSpecStr, Long.class, Object.class);
        //获取特有规格参数值的字符串类型
        String specialSpecStr = spuDetail.getSpecialSpec();
        //将字符串类型的特有规格参数转成对象
        Map<Long, List<Object>> specialSpecObj = JsonUtils.nativeRead(specialSpecStr, new TypeReference<Map<Long, List<Object>>>() {});
        //遍历specParams集合
        specParams.forEach(specParam -> {
            //获取key
            String key = specParam.getName();
            //获取value
            Object value = null;
            //区分value的来源
            if(specParam.getGeneric()){
                //通用规格参数
                value = genericSpecObj.get(specParam.getId());
            }else {
                //特有规格参数
                value = specialSpecObj.get(specParam.getId());
            }
            //如果是数字类型，则把数字兑换成区间
            if(specParam.getNumeric()){
                value = chooseSegment(value, specParam);
            }
            //给规格参数所在的map赋值
            specs.put(key, value);
        });

        //初始化Goods对象
        Goods goods = new Goods();
        goods.setId(spuDTO.getId());
        goods.setSpuName(spuDTO.getName());
        goods.setSubTitle(spuDTO.getSubTitle());
        goods.setBrandId(spuDTO.getBrandId());
        goods.setCategoryId(spuDTO.getCid3());
        goods.setCreateTime(spuDTO.getCreateTime().getTime());
        goods.setSkus(JsonUtils.toString(skuMaps));
        goods.setPrice(prices);
        goods.setAll(all);
        goods.setSpecs(specs);
        return goods;
    }

    private String chooseSegment(Object value, SpecParam p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * -------------------------------------------渲染搜索页面数据提供-------------------------------------------
     * @param request
     * @return
     */
    public Map<String, Object> loadSearchPage(SearchRequest request) {
        //获取商品数据分页信息
        PageResult<GoodsDTO> pageResult = itemPageQuery(request);
        //获取过滤条件列表
        Map<String, List<?>> filterConditions = aggQuery(request);
        //创建结果map
        Map<String, Object> result = new HashMap<>();
        result.put("filterConditions", filterConditions);//过滤条件结果
        result.put("itemsList", pageResult.getItems());//商品数据列表
        result.put("totalCount", pageResult.getTotal());//总记录数
        result.put("totalPages", pageResult.getTotalPage());//总页数
        return result;
    }

    /**
     * 查询过滤条件
     * @param request
     * @return
     */
    private Map<String, List<?>> aggQuery(SearchRequest request) {
        //初始化一个结果map对象
        Map<String, List<?>> resultMap = new LinkedHashMap<>();
        //------------------------------封装分类和品牌的聚合结果----------------------------------
        //提供一个封装复杂索引库查询的条件封装对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //封装分页信息   【聚合查询，分页可以不要】
        nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 1));
        //封装要查询的字段  类似于select后面的字段    【聚合查询，查询的字段可以不要】
        nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
        //封装查询条件  类似于where后面的条件
        nativeSearchQueryBuilder.withQuery(createQueryBuilder(request));
        //提供分类聚合的名称
        String categoryAggName = "categoryAggName";
        //封装分类聚合结果
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field("categoryId"));
        //提供品牌聚合的名称
        String brandAggName = "brandAggName";
        //封装品牌聚合结果
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field("brandId"));
        //聚合查询
        AggregatedPage<Goods> aggResult = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), Goods.class);
        //得到所有的聚合结果
        Aggregations aggregations = aggResult.getAggregations();
        //通过分类聚合名称得到分类聚合的桶的集合
        Terms categoryAgg = aggregations.get(categoryAggName);
        //将分类聚合结果做处理并放入结果map中
        List<Long> cids = handlerCategoryAgg(resultMap, categoryAgg);
        //通过品牌聚合名称得到品牌聚合的桶的集合
        Terms brandAgg = aggregations.get(brandAggName);
        //将品牌聚合结果做处理并放入结果map中
        handlerBrandAgg(resultMap, brandAgg);
        //------------------------------封装动态过滤条件聚合结果----------------------------------
        handlerActiveFilterAgg(resultMap, cids, createQueryBuilder(request));
        return resultMap;
    }

    //封装动态过滤条件聚合结果
    private void handlerActiveFilterAgg(Map<String, List<?>> resultMap, List<Long> cids, QueryBuilder queryBuilder) {
        cids.forEach(cid->{
            //提供一个封装复杂索引库查询的条件封装对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            //封装分页信息   【聚合查询，分页可以不要】
            nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 1));
            //封装要查询的字段  类似于select后面的字段    【聚合查询，查询的字段可以不要】
            nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
            //封装查询条件  类似于where后面的条件
            nativeSearchQueryBuilder.withQuery(queryBuilder);

            //根据分类id查询出所有参与搜索的规格参数的集合
            List<SpecParam> specParams = itemClient.findSpecParams(null, cid, true);
            //遍历
            specParams.forEach(specParam -> {
                //提供聚合的名称
                String aggName = specParam.getName();
                //提供要聚合的域名称
                String field = "specs."+aggName+".keyword";
                //封装聚合结果
                nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(aggName).field(field));
            });
            //聚合查询
            AggregatedPage<Goods> aggResult = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), Goods.class);
            //得到所有的聚合结果
            Aggregations aggregations = aggResult.getAggregations();

            //循环从聚合结果中获取到对应的规格参数聚合结果
            specParams.forEach(specParam -> {
                //提供聚合的名称
                String aggName = specParam.getName();
                //根据名称获取聚合结果集合
                Terms specParamAgg = aggregations.get(aggName);
                //获取聚合记过中桶的key的集合
                List<String> specParamsValue = specParamAgg.getBuckets()
                        .stream()
                        .map(Terms.Bucket::getKeyAsString)
                        .collect(Collectors.toList());
                //把聚合结果放入map中
                resultMap.put(aggName, specParamsValue);
            });
        });
    }

    //将品牌聚合结果做处理并放入结果map中
    private void handlerBrandAgg(Map<String, List<?>> resultMap, Terms brandAgg) {
        //收集到品牌聚合结果中所有的品牌id的集合
        List<Long> bids = brandAgg.getBuckets()
                .stream()
                .map(Terms.Bucket::getKeyAsNumber)
                .map(Number::longValue)
                .collect(Collectors.toList());
        //根据品牌id的集合查询品牌对象的集合
        List<Brand> brands = itemClient.findBrandsByIds(bids);
        resultMap.put("品牌", brands);
    }

    //将分类聚合结果做处理并放入结果map中
    private List<Long> handlerCategoryAgg(Map<String, List<?>> resultMap, Terms categoryAgg) {
        //收集到分类聚合结果中所有的分类id的集合
        List<Long> cids = categoryAgg.getBuckets()
                .stream()
                .map(Terms.Bucket::getKeyAsNumber)
                .map(Number::longValue)
                .collect(Collectors.toList());
        //根据分类id集合查询分类对象集合
        List<Category> categories = itemClient.findCategoriesByIds(cids);
        //把结果放入map中
        resultMap.put("分类", categories);
        return cids;
    }

    /**
     * 查询商品分页数据
     * @param request
     * @return
     */
    private PageResult<GoodsDTO> itemPageQuery(SearchRequest request) {
        //提供一个封装复杂索引库查询的条件封装对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //用2个参数如时间、价格排序
        //nativeSearchQueryBuilder.withSort(new FieldSortBuilder("createTime"));
        String sortParam = request.getSortParam();
        if (sortParam!=null && sortParam!=""){
            nativeSearchQueryBuilder.withSort(new FieldSortBuilder(sortParam));
        }
        //封装分页信息
        nativeSearchQueryBuilder.withPageable(PageRequest.of(request.getPage()-1, request.getSize()));
        //封装要查询的字段  类似于select后面的字段
        nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "spuName", "subTitle", "skus"}, null));
        //封装查询条件  类似于where后面的条件
        nativeSearchQueryBuilder.withQuery(createQueryBuilder(request));
        //封装高亮字段
        HighlightUtils.highlightField(nativeSearchQueryBuilder, "spuName");
        //索引库分页查询
        AggregatedPage<Goods> pageResultEs = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), Goods.class, HighlightUtils.highlightBody(Goods.class, "spuName"));
        //获取Goods列表
        List<Goods> goodsList = pageResultEs.getContent();
        if(CollectionUtils.isEmpty(goodsList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        //创建自定义分页对象
        PageResult<GoodsDTO> pageResult = new PageResult<>(
                pageResultEs.getTotalElements(),
                Long.valueOf(pageResultEs.getTotalPages()),
                BeanHelper.copyWithCollection(goodsList, GoodsDTO.class)
        );
        return pageResult;
    }

    /**
     * 查询条件封装
     */
    private QueryBuilder createQueryBuilder(SearchRequest request) {
        //创建一个过滤条件查询对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //添加搜索查询
        boolQuery.must(QueryBuilders.multiMatchQuery(request.getKey(), "all", "spuName").operator(Operator.AND));
        //得到过滤条件
        Map<String, Object> filterParams = request.getFilterParams();
        //判断是否有过滤条件
        if(CollectionUtils.isNotEmpty(filterParams)){
            //遍历过滤条件
            filterParams.entrySet().forEach(entry->{
                //得到key
                String key = entry.getKey();
                //对key进行处理
                if(StringUtils.equals(key, "分类")){
                    key = "categoryId";
                }else if(!StringUtils.equals(key, "brandId")){
                    key = "specs."+key+".keyword";
                }
                //得到value
                Object value = entry.getValue();
                //添加过滤查询
                boolQuery.filter(QueryBuilders.termQuery(key, value));
            });
        }
        return boolQuery;
    }

    /**
     * 修改搜索页面的page触发的处理器
     */
    public List<GoodsDTO> pageChange(SearchRequest request) {
        //获取商品数据分页信息
        PageResult<GoodsDTO> pageResult = itemPageQuery(request);
        return pageResult.getItems();
    }

    public void addIndex(Long id) {
        SpuDTO spuDTO = itemClient.findSpuDTOById(id);
        Goods goods = buildGoods(spuDTO);
        searchRepository.save(goods);
    }

    public void delIndex(Long id) {
        searchRepository.deleteById(id);
    }
}
